package info.marlan.sipgate;

import info.marlan.sipgate.model.HistoryEntry;
import info.marlan.util.ConvertUtil;
import info.marlan.util.DBHelper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 
 * @author mark@marlan.info
 *
 */

public class LogListActivity extends ListActivity implements ListView.OnScrollListener{
	public static String WIDGETID = "widgetid";
	private DBHelper dbHelper;
	private List<HistoryEntry> entries;
	private int countEntries;
	private int offset;
	private int limit = 20;
	private LogAdapter adapter;
	private int priorFirst = -1;
	private LinearLayout footerView;
	private int widgetid;
	private ArrayList<WeakReference<DataSetObserver>> dataObservers = 
	    new ArrayList<WeakReference<DataSetObserver>>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		widgetid = getIntent().getExtras().getInt(WIDGETID);
		dbHelper = new DBHelper(this);
		entries = dbHelper.getHistoryEntries(limit, offset, widgetid);
		countEntries = dbHelper.countHistoryEntries(widgetid);
		adapter = new LogAdapter(this);
		setListAdapter(adapter);
		getListView().setOnScrollListener(this);
		footerView = (LinearLayout) findViewById(R.id.loading);
		footerView.setVisibility(View.GONE);
		
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		Intent contentIntent = new Intent(Intent.ACTION_DIAL,Uri.parse(ConvertUtil.getCallNumber(entries.get(position).getRemoteUri())));
		startActivity(contentIntent);
	}
	
	static class ViewHolder {
		TextView date;
		TextView tos;
		TextView remote;
		TextView local;
		ImageView status;
	}
	public class LogAdapter extends BaseAdapter {

		private LoadDataSetObserver observer = new LoadDataSetObserver();

		private class LoadDataSetObserver extends DataSetObserver {
			@Override
			public void onChanged() {
				footerView.setVisibility(View.GONE);
				notifyDataSetChanged();
			}

			@Override
			public void onInvalidated() {
				notifyDataSetInvalidated();
			}
		}
		
		private Activity context;

		public LogAdapter(Activity c) {
			context = c;
			addObserver(observer);
		}

		public int getCount() {
			return entries== null ? 0:entries.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;

			if (convertView == null) {
				convertView = context.getLayoutInflater().inflate(R.layout.row,null);
				holder = new ViewHolder();
				holder.status = (ImageView) convertView.findViewById(R.id.status);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.remote = (TextView) convertView.findViewById(R.id.remote);
				holder.local = (TextView) convertView.findViewById(R.id.local);
				holder.tos = (TextView) convertView.findViewById(R.id.tos);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final HistoryEntry entry = entries.get(position);
			holder.status.setImageResource(ConvertUtil.getStatusIcon(entry.getStatus()));
			holder.date.setText(ConvertUtil.getDisplayTimestamp(entry.getTimestamp()));
			holder.remote.setText(entry.getPhoneBookName());
			holder.local.setText(ConvertUtil.getBaseNumber(entry.getLocalUri()));
			holder.tos.setText(entry.gettOS());

			return convertView;
		}
	}
	
    public void addObserver(DataSetObserver observer) {
        WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
        dataObservers.add(obs);
    }
    
    public void notifyObservers() {
        final ArrayList<WeakReference<DataSetObserver>> observers = dataObservers;
        final int count = observers.size();
        for (int i = count - 1; i >= 0; i--) {
            WeakReference<DataSetObserver> weak = observers.get(i);
            DataSetObserver obs = weak.get();
            if (obs != null) {
                obs.onChanged();
            } else {
                observers.remove(i);
            }
        }
    }
	

	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		if (visibleItemCount < totalItemCount && (firstVisibleItem + visibleItemCount == totalItemCount)) {

			if (firstVisibleItem != priorFirst) {
				priorFirst = firstVisibleItem;
				onLastListItemDisplayed(totalItemCount, visibleItemCount);
			}
		}
		
	}
	protected void onLastListItemDisplayed(int total, int visible) {
		if (total < countEntries) {
		footerView.setVisibility(View.VISIBLE);
		requestUpdate();
		}
	}
	
	protected void requestUpdate(){
	//	Log.v(WidgetProvider.LOGTAG,  "requestUpdate" );
		if((offset + limit) < countEntries){
			offset = offset + limit;
			List<HistoryEntry>  newEntries = dbHelper.getHistoryEntries(limit, offset, widgetid);
			if(newEntries!=null){
				entries.addAll(newEntries);
				notifyObservers();
			}
		}
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(dbHelper!=null){
		dbHelper.cleanup();
		dbHelper=null;
		}
	}

}
